package com.sita.bluetactivity.MineFragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.ArraySet;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.sita.bluetactivity.Base.BaseActivity;
import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.BaseValue;
import com.sita.bluetactivity.Event.RoundtoFindEvent;
import com.sita.bluetactivity.MyClass.BindVehicle;
import com.sita.bluetactivity.NewBlueTooth.BtService;
import com.sita.bluetactivity.NewBlueTooth.StopFindEvent;
import com.sita.bluetactivity.R;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import de.greenrobot.event.EventBus;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.BLUETOOTH;
import static android.Manifest.permission.BLUETOOTH_ADMIN;

/**
 * Created by Jason on 2016/10/10.
 */
public class FindVehicleBtActivity extends BaseActivity implements View.OnClickListener,onClickItem {
    private TextView head;
    private LinearLayout back, bt_Msg;
    private TextView findBt;
    private RecyclerView bt_equip;
    private ProgressDialog pd;
    private BtEquipmentAdapter adapter;
    private BtService.BtBinder btBinder;
    private Switch aSwitch;
    private static Handler handler = new Handler();
    private boolean mScanning = true;
    private Intent intentService;
    final int REQ_LOCATION = 0x12;
    private BluetoothAdapter bluetoothAdapter;
    private ConnectSuccessBroad connectSuccessBroad = new ConnectSuccessBroad();
    private List<BluetoothDevice> bluetoothDeviceswzb = new ArrayList<>();
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            btBinder = (BtService.BtBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            btBinder = null;
        }
    };
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device == null) {
                return;
            }
          //  Log.e("11000111000",device.getName());
            //刷新的回调方法
            if (bluetoothDeviceswzb.size() > 0 && device.getName()!=null) {

                int f = 0;
                for (int i = 0; i < bluetoothDeviceswzb.size(); i++) {
                    if (bluetoothDeviceswzb.get(i).getAddress().equals(device.getAddress())) {
                        //重名
                        f = 1;
                    }
                }
                if (f == 0 && device.getName() != null&&device.getName().substring(0,4).equals("SITA")) {
                    BaseValue.HasBtDevice = true;
                    bluetoothDeviceswzb.add(device);
                    adapter.setData(device, FindVehicleBtActivity.this);
                }
            } else {
                if (device.getName() != null&&device.getName().substring(0,4).equals("SITA")) {
                    BaseValue.HasBtDevice = true;
                    bluetoothDeviceswzb.add(device);
                    adapter.setData(device, FindVehicleBtActivity.this);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intentService = new Intent(this, BtService.class);
        bindService(intentService, connection, BIND_AUTO_CREATE);
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.sita.bluetactivity.ISOK");
        registerReceiver(connectSuccessBroad, filter);

    }

    @Override
    protected void initData() {

        bluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
        back.setOnClickListener(this);
        back.setVisibility(View.VISIBLE);
        head.setText("搜索车辆");
        findBt.setOnClickListener(this);
        adapter = new BtEquipmentAdapter(this);
        bt_equip.setLayoutManager(new LinearLayoutManager(this));
        bt_equip.setAdapter(adapter);
        if (bluetoothAdapter.enable()) {
            aSwitch.setChecked(true);
            bt_Msg.setVisibility(View.VISIBLE);
        } else {
            bt_Msg.setVisibility(View.INVISIBLE);
            aSwitch.setChecked(false);
        }
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    bt_Msg.setVisibility(View.VISIBLE);
                    bluetoothAdapter.enable();
                } else {
                    bt_Msg.setVisibility(View.INVISIBLE);
                    bluetoothAdapter.disable();
                }
            }
        });
    }

    @Override
    protected void initView() {
        applyPermission();
        bt_equip = bindView(R.id.bt_device);
        findBt = bindView(R.id.find_bt);
        head = bindView(R.id.head_tx);
        back = bindView(R.id.back_layout);
        aSwitch = bindView(R.id.open_Bt);
        bt_Msg = bindView(R.id.Bt_msg);
    }

    @Override
    protected int getId() {
        return R.layout.activity_findvehiclebt;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.find_bt:
                BaseValue.isFirstConnection = true;
                //点击连接时候需要的Binder
                pd = ProgressDialog.show(this, null, "搜索连接中...");
                Log.e("1000000000000001", BaseValue.BtIsConnection + "");

                if (BaseValue.BtIsConnection) {
                    btBinder.disConnected();
                }
                scanLeDevice(true);
                break;
        }
    }

    @Override
    public void onBtClick(BluetoothDevice device) {
        //点击蓝牙设置
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        unregisterReceiver(connectSuccessBroad);

    }

    public static void JumpIntent(Context context) {
        Intent intent = new Intent(context, FindVehicleBtActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    //搜索蓝牙设备
    private void scanLeDevice(final boolean enable) {

        if (enable) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    bluetoothAdapter.stopLeScan(mLeScanCallback);
                    connectDevice();
                }
            }, 3000);
            BaseValue.HasBtDevice = false;
            mScanning = true;
            bluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            bluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

    public void applyPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, BLUETOOTH_ADMIN,BLUETOOTH},
                REQ_LOCATION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQ_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void connectDevice() {
        if (bluetoothDeviceswzb.size()>0) {
            btBinder.getDeviceList(bluetoothDeviceswzb);
            if (btBinder != null) {
                btBinder.connection(bluetoothDeviceswzb.get(0));//连接时候打开了计时器
            }
        } else {
            Toast.makeText(FindVehicleBtActivity.this, "无设备", Toast.LENGTH_SHORT).show();
            btBinder.disConnected();
        }

        pd.dismiss();

    }

    //当连接成功以后调回到车辆页面
    private class ConnectSuccessBroad extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
          finish();
        }
    }
    //解绑的时候如果有蓝牙连接则断开连接


}
